<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2025/5/19/019
 * Time: 16:47
 */

namespace app\common\service;

use think\facade\Log;

class KuaishouService
{
    private $url = 'https://open.kuaishou.com';
    protected $appid;

    protected $appsecret;

    public function __construct()
    {
        $set = sysconfig('forward');
        $this->appid = empty($set['k_appid']) ? '' : $set['k_appid'];
        $this->appsecret = empty($set['k_secret']) ? '' : $set['k_secret'];
        $this->k_xiaochengxu = empty($set['k_xiaochengxu']) ? '' : $set['k_xiaochengxu'];

    }

    public function kuaishouQrcode($uid, $id)
    {

        $request = Request();
        $domain = $request->host();
        $callbackUrl = urlencode("https://" . $domain . "/mobile/ExternalAccount/kuaishouQrcodeRedirect?uid=" . $uid . '&id=' . $id.'&type=' . 2);
        if ( $this->k_xiaochengxu == 1 ){
            $url =  $this->url."/oauth2/authorize?app_id=" . $this->appid . "&response_type=code&scope=user_info,user_video_publish,user_video_info,user_video_mp_plc&redirect_uri=" . $callbackUrl;

        }else{
            $url =  $this->url."/oauth2/authorize?app_id=" . $this->appid . "&response_type=code&scope=user_info,user_video_publish,user_video_info&redirect_uri=" . $callbackUrl;
        }

        $qrcode = common_qr_code($url, 'repost');
        if ($qrcode) {
            return array(
                'code' => 1,
                'data' => $qrcode,
                'msg' => 'success'
            );
        } else {
            return array(
                'code' => 0,
                'data' => [],
                'msg' => '获取失败'
            );

        }
    }

    public function kuaishouAccessToken($code)
    {
        $forwardSet = sysconfig('forward');
        $k_appid = $forwardSet['k_appid'];
        $k_secret = $forwardSet['k_secret'];
        $url = $this->url. "/oauth2/access_token?app_id=" . $k_appid . "&app_secret=" . $k_secret . "&code=" . $code . "&grant_type=authorization_code";
        $obj = httpGet($url);
        $data = json_decode($obj, true);

        if ($data['result'] == 1) {
            $return = array(
                'code' => 1,
                'data' => $data,
                'msg' => 'success'
            );
        } else {
            $return = array(
                'code' => 0,
                'data' => [],
                'msg' => isset($result['msg']) ? $data['msg'] : ''
            );
        }
        return $return;
    }

    public function kuaishouUserinfo($access_token)
    {
        $user_url = $this->url. "/openapi/user_info?app_id=" . $this->appid . "&access_token=" . $access_token;
        $user_info = httpGet($user_url);
        $data = json_decode($user_info, true);
        if ($data['result'] == 1) {
            $return = array(
                'code' => 1,
                'data' => $data,
                'msg' => 'success'
            );
        } else {
            $return = array(
                'code' => 0,
                'data' => [],
                'msg' => isset($result['msg']) ? $data['msg'] : ''
            );
        }
        return $return;
    }

    public function kuaishouRefreshToken($refresh_token)
    {
        $forwardSet = sysconfig('forward');
        $k_appid = $forwardSet['k_appid'];
        $k_secret = $forwardSet['k_secret'];
        $url = $this->url."/oauth2/refresh_token?app_id=" . $k_appid . "&app_secret=" . $k_secret . "&refresh_token=" . $refresh_token . "&grant_type=refresh_token";

        $obj = httpGet($url);
        $data = json_decode($obj, true);

        if ($data['result'] == 1) {
            $return = array(
                'code' => 1,
                'data' => $data,
                'msg' => 'success'
            );
        } else {
            $return = array(
                'code' => 0,
                'data' => [],
                'msg' => isset($result['msg']) ? $data['msg'] : ''
            );
        }
        return $return;
    }

    function apiPost($url, $header, $data = NULL)
    {
        $request = Request();
        $domain = $request->host();
        $headers = array(
            'Content-Type: x-www-form-urlencoded'
        );
        if (!empty($header)) {
            $headers = array_merge($headers, $header);
        }
        $userAgent = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 600); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); // 类型为json
        $result = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Error POST' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        return $result; // 返回数据
    }



    public function releaseKuaishuoVideo($param)
    {
        $url = $this->url."/openapi/photo/start_upload?app_id=" . $this->appid . "&access_token=" . $param['access_token'];
        $arr = wtw_request($url, "{}");
        $arr1 = json_decode($arr, true);

        if ($arr1['result'] == 1) {
            $upload_token = $arr1['upload_token'];
            $endpoint = $arr1['endpoint'];
            $upload_url = "http://{$endpoint}/api/upload?upload_token=" . $upload_token;
            $reply = http_binary($param['complete_video'], $upload_url); ;
            $data = json_decode($reply, true);
            if ($data['result'] == 1) {
                $publish_url =  $url = $this->url."/openapi/photo/publish?access_token=" . $param['access_token'] . "&app_id=" . $this->appid . "&upload_token=" . $upload_token;
                $send_data = array(
                    'cover' => $param['complete_cover'],
                    'caption' => $param['caption']
                );
                if (isset($param['merchant_product_id']) && $param['merchant_product_id']){
                    $send_data['merchant_product_id'] =  $param['merchant_product_id'];
                }
              /*  if (isset($param['anchorUrl']) && $param['anchorUrl']){

                }*/
                $arr2 = wtw_request($publish_url, $send_data);

                $arr3 = json_decode($arr2, true);
                if ($arr3['result'] == 1) {
                    $return = array(
                        'code' => 1,
                        'data' => $arr3['video_info'],
                        'msg' => 'success'
                    );
                } else {
                    $return = array(
                        'code' => 0,
                        'data' => [],
                        'msg' => isset($result['msg']) ? $data['msg'] : ''
                    );
                }

            }
        }
        return $return;
    }


    public function bind($data){
        $url = $this->url."openapi/photo/mp_plc/bind";
       $result =  $this->apiPost($url,[],$data);
       $data['app_id'] = $this->appid;
        if (isset($result['result']) && $result['result'] == 200) {
            return array(
                'code' => 1,
                'data' => $result['data'],
                'msg' => 'success'
            );
        } else {
            return array(
                'code' => 0,
                'data' => [],
                'msg' => isset($result['msg']) ? $result['msg'] : ''
            );
        }
    }


}